package com.ehotting.edsta.mqbd.test.zw.controller;

import com.ehotting.edsta.mqbd.test.zw.config.WebsocketConfigurator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
//@RestController
@Component
@ServerEndpoint(value="/websocket.ws/{agentId}/{mainProjectId}", configurator = WebsocketConfigurator.class)
public class SimulationWsController {

    public static ConcurrentHashMap<String, Session> webSocketSet = new ConcurrentHashMap<>();
    public static ConcurrentHashMap<String, String> webSocketIdSet = new ConcurrentHashMap<>();



    /**
     * 连接建立成功调用的方法
     * @param agentId
     * @param session
     * @throws Exception
     */
    @OnOpen
    public void onOpen(@PathParam("agentId") String agentId,
                       @PathParam("mainProjectId") String mainProjectId,
                       Session session) throws Exception {
        webSocketSet.put(agentId/*+"-"+mainProjectId*/, session);
        webSocketIdSet.put(session.getId(),agentId/*+"-"+mainProjectId*/);
    }

    /**
     * 连接关闭调用方法
     */
    @OnClose
    public void onClose(Session session) {
        webSocketSet.remove(session);
        log.info("websocket有一连接关闭");
    }

    /**
     * 收到客户端消息后调用方法
     * @param message
     * @param session
     */
    @OnMessage
    public void onMessage(String message, Session session) throws Exception{
        if (session.isOpen()) {
            session.getBasicRemote().sendText(message);
        }
    }

    /**
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("websocket 发生异常", error);
        webSocketSet.remove(session);
    }

    /**
     * 向客户端发送消息推送
     * @param message
     * @throws Exception
     */
    public void sendMessage(Session session,String message) throws Exception {
        synchronized (session) {
            if (session.isOpen()) {
//                log.info("session.isOpen>>>>>>msg len is {}",message.length());
                session.getBasicRemote().sendText(message);
            }
        }
    }



    /**
     * 发送信息给指定ID用户，如果用户不在线则返回
     * @param message
     * @param sendUserId
     * @throws IOException
     */
    public void sendUserMessage(String message,String sendUserId) throws Exception {

        if(webSocketSet.get(sendUserId) != null){
            sendMessage(webSocketSet.get(sendUserId),message);
        }else{
            log.info("当前用户不在线：" + sendUserId);
        }
    }

    /**
     * 推送信息给所有用户
     * @param message
     */
    public void sendAllMessage(String message) {
        log.info("推送信息给所有用户>>>>>>>message.length is {}",message.length());

        for(String key : webSocketSet.keySet()){
            try {
                sendMessage(webSocketSet.get(key),message);
            }catch (Exception e){
                log.info("推送信息给所有用户异常：" + e.getMessage());
            }
        }
    }

}